package com.truth.lock.executor.zookeeper;

import com.truth.lock.enumeration.TruthLockType;
import com.truth.lock.executor.TruthLockExecutor;
import com.truth.lock.factory.TruthExecutorBeanFactory;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;

import java.util.concurrent.TimeUnit;

/**
 * @author Truth
 */
public class ZookeeperMutexLockExecutor implements TruthLockExecutor<InterProcessMutex > {

    private final CuratorFramework curatorFramework;

    public ZookeeperMutexLockExecutor(CuratorFramework curatorFramework) {
        this.curatorFramework = curatorFramework;
    }

    @Override
    public InterProcessMutex acquire(String lockKey, String lockValue, long expire, long acquireTimeout) {
        try {
            String node = "/curator/truthLock/%s";
            InterProcessMutex mutex = new InterProcessMutex(curatorFramework, String.format(node, lockKey));
            boolean locked = mutex.acquire(acquireTimeout, TimeUnit.MILLISECONDS);
            return acquireLockInstance(locked, mutex);
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public boolean releaseLock(String key, String value, InterProcessMutex lockInstance) {
        try {
            lockInstance.release();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        TruthExecutorBeanFactory.register(TruthLockType.ZOOKEEPER_MUTEX_LOCK, this);
    }
}
